#include "UnitaryLinearRegression.h"
#include <fstream>
#include <sstream>
#include <iostream>

#define _USE_MATH_DEFINES
#define WITHOUT_NUMPY
#include <matplotlibcpp.h>

bool UnitaryLinearRegression::importData(std::string const &path)
{
	std::ifstream file(path);
	if (!file.is_open())
		return false;

	std::string line, number;
	double x, y;
	while (std::getline(file, line))
	{
		std::stringstream ss(line);
		std::getline(ss, number, ',');
		x = std::stod(number);
		std::getline(ss, number, ',');
		y = std::stod(number);
		data.push_back(std::make_pair(x, y));
	}
	std::cout << "Data imported: " << data.size() << std::endl;
	return true;
}
void UnitaryLinearRegression::calc()
{
	double sumX = 0.0, sumX2 = 0.0, _x = 0.0;
	double dx = 0.0;
	for (std::pair<double, double> &p : data)
	{
		sumX += p.first;
		sumX2 += p.first * p.first;
	}
	_x = sumX / data.size();

	double part1 = 0.0, part2 = 0.0;
	for (std::pair<double, double> &p : data)
		part1 += (p.first - _x) * p.second;
	part2 = sumX2 - sumX * sumX / data.size();

	w = part1 / part2;
	for (std::pair<double, double> &p : data)
		b += p.second - w * p.first;
	b /= data.size();
}

void UnitaryLinearRegression::show()
{
	std::cout << "w: " << w << " b: " << b << std::endl;
	std::vector<double> realX, realY;
	std::vector<double> predictX, predictY;
	for (std::pair<double, double> &p : data)
		realX.push_back(p.first), realY.push_back(p.second),
		predictX.push_back(p.first), predictY.push_back(w * p.first + b);
	matplotlibcpp::figure_size(800, 600);
	matplotlibcpp::scatter(realX, realY);
	matplotlibcpp::plot(predictX, predictY, "orange");
	matplotlibcpp::title("Unitary Linear Regression");
	matplotlibcpp::show();
}